import {
  Breadcrumb,
  Button,
  Card,
  Form,
  Input,
  message,
  Modal,
  Radio,
  Space,
  Upload,
} from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { Link } from 'react-router-dom';
import Channel from 'components/Channel';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import styles from './index.module.scss';
import { baseURL } from 'utils/request';
import { getToken } from 'utils/strorage';
import { UploadOutlined } from '@ant-design/icons';
import { useHistory } from 'react-router-dom';
import {
  editArticleAPI,
  getArticleByIdAPI,
  pubishArticleAPI,
} from 'api/article';
import { useParams } from 'react-router-dom';

/*
 学习目标：实现编辑文章
 
   
*/

const allowFileType = ['image/jpeg', 'image/jpg', 'image/png'];
export default function ArticlePublish() {
  const draftRef = useRef(false);
  const history = useHistory();
  const { id } = useParams();
  const [imgUrl, setImgUrl] = useState('');
  const [fileList, setFileList] = useState([]);
  const [type, setType] = useState(1);

  const formRef = useRef();

  const loadDataById = async (id) => {
    const { data } = await getArticleByIdAPI(id);

    formRef.current.setFieldsValue({ ...data, type: data.cover.type });

    setType(data.cover.type);

    setFileList(data.cover.images.map((item) => ({ url: item })));
  };

  useEffect(() => {
    if (id) {
      loadDataById(id);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleValuseChange = (changedValues, allValues) => {
    // changedValues代表此时值改变的字段对象，allValues所有的字段组成对象
    if (changedValues.type !== undefined) {
      setType(changedValues.type);
      if (fileList.length > changedValues.type) {
        const newList = fileList.slice(0, changedValues.type); // 包前不包后
        setFileList(newList);
      }
    }
  };

  const props = {
    // accept自定义弹出的上传窗口，显示哪些文件类型
    accept: ['.jpeg,.jpg,.png'],
    name: 'image',
    action: baseURL + '/v1_0/upload',
    headers: {
      authorization: `Bearer ${getToken()}`,
    },
    onChange(info) {
      setFileList(info.fileList);

      if (info.file.status === 'done') {
        message.success(`${info.file.name} 上传成功`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
      }
    },

    onPreview: (file) => {
      setImgUrl(file.url || file.thumbUrl);
    },

    beforeUpload: (file) => {
      if (!allowFileType.includes(file.type)) {
        message.warning('不允许上传的文件类型');

        return Upload.LIST_IGNORE;

        // 返回false可以阻止上传，会把不允许上传的图片，显示在前端界面上
        // return false;
      }
    },
  };

  const handlePublish = async (values) => {
    // 2. 修复数据格式问题：url有可能是从服务器回填的，有可能是刚上传的
    const urlList = fileList.map((item) => item.url || item.response.data.url);

    const cover = {
      type,
      Images: urlList,
    };

    const formData = {
      ...values,
      cover,
    };

    delete formData.type;
    delete formData.images;

    if (fileList.length !== type) {
      message.warning('图片数量不正确，请上传');
      return;
    }

    // 3. 判断是否存在id，存在id调用编辑接口，不存在id调用发布接口
    if (id) {
      await editArticleAPI({ ...formData, id }, draftRef.current);
      message.success('编辑成功', 1);
      history.push('/list');
      return;
    }

    await pubishArticleAPI(formData, draftRef.current);
    message.success('发布成功', 1);
    history.push('/list');
  };

  return (
    <div className={styles.publish}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>{id ? '编辑' : '发布'}文章</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          ref={formRef}
          onFinish={handlePublish}
          size="large"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          initialValues={{ content: '', type: 1 }}
          onValuesChange={handleValuseChange}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入标题' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[
              {
                required: true,
                message: '请选择频道',
              },
            ]}
          >
            <Channel />
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[
              {
                required: true,
                message: '内容不能为空',
              },
              {
                validator: (_, value) => {
                  if (value === '<p><br></p>') {
                    return Promise.reject(new Error('内容不能为空'));
                  }
                  return Promise.resolve();
                },
              },
            ]}
          >
            <ReactQuill />
          </Form.Item>
          <Form.Item label="封面" name="type">
            <Radio.Group>
              <Radio value={1}>单图</Radio>
              <Radio value={3}>三图</Radio>
              <Radio value={0}>无图</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item name="images" wrapperCol={{ offset: 4 }}>
            <Upload {...props} listType="picture-card" fileList={fileList}>
              {fileList.length < type && <Button icon={<UploadOutlined />} />}
            </Upload>
          </Form.Item>
          <Form.Item
            wrapperCol={{
              offset: 4,
            }}
          >
            <Space>
              <Button type="primary" htmlType="submit">
                {id ? '编辑' : '发布'}文章
              </Button>
              <Button
                type="primary"
                htmlType="submit"
                onClick={() => {
                  draftRef.current = true;
                }}
              >
                存草稿
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
      <Modal
        visible={!!imgUrl}
        footer={null}
        style={{ width: 470 }}
        onCancel={() => setImgUrl('')}
      >
        <img src={imgUrl} alt="" />
      </Modal>
    </div>
  );
}
